﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PersonaLibrary.Search
{
	public sealed class FioSearchCriteria : StringSearchCriteria
	{
		private static string PrepareValue(string value, string @operator, string valueDecorator)
		{
			string[] splitResult = value.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

			StringBuilder result = new StringBuilder();

			for (int i = 0; i < 3; i++)
			{
				if(i >= splitResult.Length)
					break;

				result.Append("(Employee.Surname ");
				result.Append(@operator);
				result.Append(" '");
				result.AppendFormat(valueDecorator, splitResult[i]);
				result.Append("' or Employee.Name ");
				result.Append(@operator);
				result.Append(" '");
				result.AppendFormat(valueDecorator, splitResult[i]);
				result.Append("' or Employee.Patronymic ");
				result.Append(@operator);
				result.Append(" '");
				result.AppendFormat(valueDecorator, splitResult[i]);
				result.Append("')");

				if(i < splitResult.Length - 1)
					result.Append(" and ");
			}

			return result.ToString();
		}

		public override void CreateWhere(StringBuilder stringBuilder)
		{
			switch (Operator)
			{
				case "Содержит":
					stringBuilder.Append(PrepareValue(Value, "like", "%{0}%"));
					break;

				case "Несодержит":
					stringBuilder.Append(PrepareValue(Value, "not like", "%{0}%"));
					break;

				case "Начинается":
					stringBuilder.Append(PrepareValue(Value, "like", "%{0}"));
					break;

				case "Заканчивается":
					stringBuilder.Append(PrepareValue(Value, "like", "{0}%"));
					break;

				case "=":
				case "!=":
					stringBuilder.Append(PrepareValue(Value, Operator, "{0}"));
					break;

				default:
					throw new Exception(string.Format("Не известный оператор '{0}'", Operator));
			}
		}
	}
}
